using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml.XPath;
using System.Xml.Xsl;
using System.Xml;
using System.Diagnostics;
using System.IO;
using System.Reflection;

namespace XmlTransformer
{
	public partial class MainForm : Form
	{
		private string resultFile = string.Empty;

		public MainForm()
		{
			InitializeComponent();
		}

		private void btnSelectXMLFile_Click(object sender, EventArgs e)
		{
			using (OpenFileDialog ofd = new OpenFileDialog())
			{
				ofd.Filter = "Xml Files|*.xml";
				if (ofd.ShowDialog() == DialogResult.OK)
				{
					this.txtXMLFile.Text = ofd.FileName;
				}
			}
		}

		private void btnSelectXSLTFile_Click(object sender, EventArgs e)
		{
			using (OpenFileDialog ofd = new OpenFileDialog())
			{
				ofd.Filter = "Xslt Files|*.xslt";
				if (ofd.ShowDialog() == DialogResult.OK)
				{
					this.txtXSLTFile.Text = ofd.FileName;
				}
			}
		}

		private void btnOK_Click(object sender, EventArgs e)
		{
			try
			{
				byte[] resultAsBytes = this.ApplyXslt(this.txtXMLFile.Text, this.txtXSLTFile.Text);

				string currentDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
				this.resultFile = Path.Combine(currentDir, this.txtResultFile.Text);
				if (File.Exists(this.resultFile))
				{
					File.Delete(this.resultFile);
				}

				File.WriteAllBytes(resultFile, resultAsBytes);

				this.btnOpen.Enabled = true;
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.ToString());
			}
		}

		private void btnOpen_Click(object sender, EventArgs e)
		{
			try
			{
				Process p = new Process();
				p.StartInfo = new ProcessStartInfo(resultFile);
				p.Start();
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.ToString());
			}
		}

		private byte[] ApplyXslt(string xmlFile, string xsltFile)
		{
			// Load the Xml doc
			XPathDocument myXPathDoc = new XPathDocument(xmlFile);

			XslCompiledTransform myXslTrans = new XslCompiledTransform();
			// Load the Xsl
			myXslTrans.Load(xsltFile);

			using (MemoryStream ms = new MemoryStream())
			{
				XsltArgumentList argList = new XsltArgumentList();

				// Do the actual transform of Xml
				myXslTrans.Transform(myXPathDoc, argList, ms);

				return ms.ToArray();
			}
		}
	}
}